/**
 * 答卷配置管理初始化
 */
var Poetry = {
		poetryData: {},
		    ztreeInstance: null,
		    validateFields: {
		    	title: {
		            validators: {
		                notEmpty: {
		                    message: '标题不能为空'
		                }
		            }
		        },
		        poetryType: {
		            validators: {
		                notEmpty: {
		                    message: '类型不能为空'
		                }
		            }
		        },
		        files: {
		            validators: {
		                notEmpty: {
		                    message: '请上传图片'
		                }
		            }
		        },
		        answer: {
		            validators: {
		                notEmpty: {
		                    message: '问题不能为空'
		                }
		            }
		        },
		        question: {
		            validators: {
		                notEmpty: {
		                    message: '请选择正确答案'
		                }
		            }
		        },
		        selectAnswer: {
		            validators: {
		                notEmpty: {
		                    message: '请选择选项标识'
		                }
		            }
		        },
		        inputAnswer: {
		            validators: {
		                notEmpty: {
		                    message: '选项答案不能为空'
		                }
		            }
		        },
		        okValue: {
		            validators: {
		                notEmpty: {
		                    message: '分数不能为空'
		                },
		                greaterThan: {
		                    value: 1
		                },
		                lessThan: {
		                    value: 100
		                }
		            }
		        }
		        
		        
		        
		        
		        
		    }
};

/**
 * 清除数据
 */
Poetry.clearData = function () {
    this.configData = {};
};

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
Poetry.set = function (key, val) {
    this.configData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
};

/**
 * 查询字典列表
 */
Poetry.search = function () {
    var queryData = {};
    queryData['condition'] = $("#condition").val();
    Poetry.table.refresh({query: queryData});
};

/**
 * 验证数据是否为空
 */
Poetry.validate = function () {
    $('#poetryForm').data("bootstrapValidator").resetForm();
    $('#poetryForm').bootstrapValidator('validate');
    return $("#poetryForm").data('bootstrapValidator').isValid();
};
/**
 * 收集数据
 */
Poetry.collectData = function () {
    this.set('title').set('poetryType').set('awardValue');
    this.configData["photo"]=$("img[class='file-preview-image kv-preview-data']").attr("src");
    this.configData["num"]=$("#content").children().length;
    var  suffix=$("input[class='file-caption-name']").val();
	if(suffix.length>0)
	{
		suffix=suffix.substring(suffix.indexOf("."),suffix.length);
	}
	this.configData["suffix"]=suffix;
    var arr = {};
    var final_result=false;
    $("#content").children().each(function(index,e)
    {
    	var obj={};
    	obj[""+(index+1)]=$(this).find("input[name='answer']").val();
    	obj["value"]=$(this).find("input[name='okValue']").val();
    	obj["Z"]=$(this).find("select[name='question']").val();	
    	var arr_obj=($(this).find("select[name='question']").val()+"").split(",");
        for(var i=0;i<arr_obj.length;i++)
        {
           var isResult=false;
    	$(this).find("select[name='selectAnswer']").each(function()
    	{

    		 obj[$(this).val()]=$(this).parent().parent().next().find("input[name='inputAnswer']").val();
    		 if(arr_obj[i]==$(this).val())
			 {
				 isResult=true;
				 return;
			 }
    	});
    	
    	 if(!isResult)
		 {
			  Feng.error("第"+(index+1)+"题请选择在答案中存在的选项!");
			  final_result=true;
    		  return;
		 }
        }
    	arr[""+(index+1)]=obj;
     
    });
    if(final_result)
    {
    	return false;
    }
    this.configData["subjects"]=JSON.stringify(arr);
    return true;
  
}

Poetry.addSubmit=function()
{
    this.clearData();
    var b=this.collectData();
    if(!b)
    {
    	return;
    }
    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/poetryConfig/poetryAdd", function (data) {
        Feng.success("添加成功!");
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.setData(this.configData);
    ajax.start();
}
$(function () {
	 $('[data-toggle="tooltip"]').tooltip();
	  Feng.initValidator("poetryForm", Poetry.validateFields);
	 $("#content").on("click","button[name='add_answer_btn']",function()
	{
	      var html='<div class="row">'
              +'<div class="form-group col-sm-3">'
              +'<div class="input-group">'
              +'<span class="input-group-addon">选项</span>'
              +'<select class="form-control" name="selectAnswer"><option value="">请选择</option><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option><option value="E">E</option><option value="F">F</option><option value="G">G</option><option value="H">H</option><option value="I">I</option><option value="J">J</option><option value="K">K</option></select>'
              +'</div></div><div class="form-group col-sm-8"><div class="input-group"><span class="input-group-addon">答案</span><input class="form-control" type="text" name="inputAnswer"></div></div>'
              +'<div class="col-sm-1"> <button type="button" name="remove_answer_btn" class="btn btn-default" data-original-title="删除答案" data-toggle="tooltip" data-placement="left"><i class="glyphicon glyphicon-minus"></i></button></div></div>';
		$(this).parent().parent().parent().append(html);
		 $('[data-toggle="tooltip"]').tooltip();
		  $("#poetryForm").data('bootstrapValidator').addField('selectAnswer', {
			   
				validators: {
					notEmpty: {
						message: '请选择选项标识'
					}
				}
			});
		  $("#poetryForm").data('bootstrapValidator').addField('inputAnswer', {
			   
				validators: {
					notEmpty: {
						message: '选项答案不能为空'
					}
				}
			});
		  
	
	});
	
	$("#poetryType").change(function()
	{
		if($(this).val()=="ZHSC")
		{
			  $("#poetryForm").data('bootstrapValidator').addField('awardValue', {
				   
					validators: {
						notEmpty: {
							message: '分数限制不能为空'
						},
		                greaterThan: {
		                    value: 1
		                },
		                lessThan: {
		                    value: 100
		                }
					}
				});
			  $('#poetryForm').data('bootstrapValidator').enableFieldValidators('awardValue', true);
		}else
		{
			
	      if(typeof($('#poetryForm').data('bootstrapValidator').options.fields["awardValue"])!="undefined")
		{
		$('#poetryForm').data('bootstrapValidator').enableFieldValidators('awardValue', false);
		}
				
			
		}
		
		
	}); 
	 
	 
	$("#content").on("click","button[name='remove_answer_btn']",function()
	{
	          $(this).parent().parent().remove();
	});
	
	$("#add_AnswerChild_btn").click(function()
	{
		var index=$(this).parent().next().next().children().length+1;
		var html='<div class="row"><div class="col-sm-12"><div class="panel panel-default"><div class="panel-heading"><span class="badge">'+index+'</span></div>'
			    +'<div class="panel-body" id="content"><div class="row"><div class="form-group col-sm-4"><div class="input-group"><span class="input-group-addon">问题</span><input name="answer" class="form-control" type="text">'
                +'</div></div><div class="form-group col-sm-5"><div class="input-group"><span class="input-group-addon">正确答案选项</span><select class="selectpicker form-control" multiple name="question" class="form-control"><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option><option value="E">E</option><option value="F">F</option><option value="G">G</option><option value="H">H</option><option value="I">I</option><option value="J">J</option><option value="K">K</option></select>'
                +'</div></div><div class="form-group col-sm-3"><div class="input-group"><span class="input-group-addon">分数</span><input class="form-control" type="text" name="okValue"></div>'
                +'</div></div><div class="row"><div class="form-group col-sm-3"><div class="input-group"><span class="input-group-addon">选项</span><select class="form-control" name="selectAnswer"><option value="">请选择</option><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option> <option value="E">E</option><option value="F">F</option><option value="G">G</option><option value="H">H</option><option value="I">I</option><option value="J">J</option><option value="K">K</option></select>'
                +'</div></div><div class="form-group col-sm-8"><div class="input-group"><span class="input-group-addon">答案</span><input class="form-control" name="inputAnswer" type="text"></div></div><div class="col-sm-1"> <button type="button" name="add_answer_btn" class="btn btn-default" data-original-title="添加答案" data-toggle="tooltip" data-placement="left"><i class="glyphicon glyphicon-plus"></i></button> </div></div></div></div></div></div>';
		if(typeof($("#content").children().last().find("div[class='panel panel-default']").children().find("button[name='remove_AnswerChild_btn']").eq(0).parent())!="undefined")
		{
			$("#content").children().last().find("div[class='panel panel-default']").children().find("button[name='remove_AnswerChild_btn']").eq(0).parent().remove();
		}
		$(this).parent().next().next().append(html);
	    $(this).parent().next().next().children().last().find("div[class='panel panel-default']").prepend('<div><button type="button" class="btn btn-default pull-right"  style="margin-right:2px;margin-top:2px;margin-bottom:2px"  name="remove_AnswerChild_btn" data-original-title="点击删除题目" data-toggle="tooltip" data-placement="left"><span class="glyphicon glyphicon-trash"></span></button></div>');
	    $('[data-toggle="tooltip"]').tooltip();
	    $('.selectpicker').selectpicker();
		  $("#poetryForm").data('bootstrapValidator').addField('answer', {
			   
				validators: {
					notEmpty: {
						message: '问题不能为空'
					}
				}
			});
		  $("#poetryForm").data('bootstrapValidator').addField('okValue', {
			   
				validators: {
					notEmpty: {
						message: '分数不能为空'
					},
	                greaterThan: {
	                    value: 1
	                },
	                lessThan: {
	                    value: 100
	                }
				}
			});
		  $("#poetryForm").data('bootstrapValidator').addField('question', {
			   
				validators: {
					notEmpty: {
						message: '请选择正确答案'
					}
				}
			});
		  $("#poetryForm").data('bootstrapValidator').addField('selectAnswer', {
			   
				validators: {
					notEmpty: {
						message: '请选择选项标识'
					}
				}
			});
		  $("#poetryForm").data('bootstrapValidator').addField('inputAnswer', {
			   
				validators: {
					notEmpty: {
						message: '选项答案不能为空'
					}
				}
			});
	});
		$("#content").on("click","button[name='remove_AnswerChild_btn']",function()
		{
			$(this).parent().parent().parent().parent().remove();
			if($("#content").children().length>1)
			{
				$("#content").children().last().find("div[class='panel panel-default']").prepend('<div><button type="button" class="btn btn-default pull-right"  style="margin-right:2px;margin-top:2px;margin-bottom:2px"  name="remove_AnswerChild_btn" data-original-title="点击删除题目" data-toggle="tooltip" data-placement="left"><span class="glyphicon glyphicon-trash"></span></button></div>');
				 $('[data-toggle="tooltip"]').tooltip();
			}

		});
		$("#content").on("change","select[name='selectAnswer']",function(){
			var is_result=false;
			if($(this).val()!="")
			{
				var temp=$(this).val();
				$(this).parent().parent().parent().siblings().find("select[name='selectAnswer']").each(function()
						{
						    if($(this).val()!="")
						    {
						    	if($(this).val()==temp)
						    	{
						    		Feng.error("选项不能相同!");
						    		is_result=true;
						    		return false;
						    	}
						    }	
						});
				if(is_result)
				{
					$(this).val("");
				}
				
			}
		});		
		
});
